package linc.fun.openai.service.impl;


import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import linc.fun.openai.domain.entity.chat.ChatUserLoginLogDO;
import linc.fun.openai.enums.ChatUserRegisterTypeEnum;
import linc.fun.openai.mapper.ChatUserLoginLogMapper;
import linc.fun.openai.service.ChatUserService;
import linc.fun.openai.service.ChatUserLoginLogService;
import linc.fun.openai.util.IdGenerator;
import linc.fun.openai.util.WebUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 前端用户登录日志业务实现类
 *
 * @author CoDeleven
 */
@Service
public class ChatUserLoginLogServiceImpl extends ServiceImpl<ChatUserLoginLogMapper, ChatUserLoginLogDO> implements ChatUserLoginLogService {

    @Resource
    private ChatUserService chatUserService;
    @Resource
    private IdGenerator idGenerator;

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @Override
    public void loginFailed(ChatUserRegisterTypeEnum registerType, Long userBindingEmailId, Long userId, String message) {
        ChatUserLoginLogDO logDO = new ChatUserLoginLogDO();
        logDO.setId(idGenerator.getId());
        logDO.setUserId(userId);
        logDO.setUserBindingEmailId(userBindingEmailId);
        logDO.setLoginStatus(false);
        logDO.setLoginType(registerType);
        logDO.setMessage(message);
        logDO.setLoginIp(WebUtil.getIp());
        this.save(logDO);
    }

    @Override
    public void loginSuccess(ChatUserRegisterTypeEnum registerType, Long userBindingEmailId, Long userId) {
        ChatUserLoginLogDO logDO = new ChatUserLoginLogDO();
        logDO.setId(idGenerator.getId());
        logDO.setUserId(userId);
        logDO.setUserBindingEmailId(userBindingEmailId);
        logDO.setLoginStatus(true);
        logDO.setLoginType(registerType);
        logDO.setMessage("success");
        logDO.setLoginIp(WebUtil.getIp());
        this.save(logDO);
        // 更新上次登录时间
        chatUserService.updateLastLoginIp(userId);
    }
}




